package cn.zyjblogs.nio.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NIOClient {
    public static void main(String[] args) {
        //得到一个网路通道
        try (SocketChannel socketChannel = SocketChannel.open()){
            //设置非阻塞
            socketChannel.configureBlocking(false);
            //提供服务端的ip 和 端口
            InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
            //链接服务器
            if (!socketChannel.connect(inetSocketAddress)){
                while (!socketChannel.finishConnect()){
                    System.out.println("因为连接需要时间，客户端不会阻塞，可以做其他工作");
                }
            }
            //如果连接成功 就发送数据
            String str = "逝水无痕客户端数据: 你好呀!";
            ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
            socketChannel.write(buffer);
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
